package com.mycode.finance.controller.app;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mycode.finance.entity.*;
import com.mycode.finance.entity.app.*;
import com.mycode.finance.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/bf")
public class BFController {
    @Autowired
    ChangeMoneyService changeMoneyService;
    @Autowired
    UserService userService;
    @Autowired
    UserChangeMoneyService userChangeMoneyService;
    @Autowired
    FlowOfFundsService flowOfFundsService;
    @Autowired
    PayMoneyService payMoneyService;
    @Autowired
    UserPayMoneyService userPayMoneyService;
    @Autowired
    TermFinancialService termFinancialService;
    @Autowired
    FundProductService fundProductService;
    @Autowired
    UserTermFinancialService userTermFinancialService;
    @Autowired
    UserFundProductService userFundProductService;
    @Autowired
    BankService bankService;
    @Autowired
    InfoService infoService;

    /**
     * 零钱理财-列表
     */
    @GetMapping("/change/list")
    public HashMap<String, Object> toChangemoney() {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<ChangeMoney> list = changeMoneyService.selectAllChangeMoney();
        resultMap.put("changeMoneyList", list);
        resultMap.put("pageTopBarInfo", "零钱理财界面");
        resultMap.put("activeUrl1", "financeActive");
        resultMap.put("activeUrl2", "changeMoneyActive");
        return resultMap;
    }

    /**
     * 工资理财-列表
     */
    @RequestMapping("/salary/list")
    public HashMap<String, Object> salaryList() {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<PayMoney> list = payMoneyService.selectAllPayMoney();
        resultMap.put("payMoneyList", list);
        resultMap.put("pageTopBarInfo", "工资理财界面");
        resultMap.put("activeUrl1", "financeActive");
        resultMap.put("activeUrl2", "payMoneyActive");
        return resultMap;
    }

    /**
     * 期限理财-列表
     */
    @RequestMapping("/term/list")
    public HashMap<String, Object> termList() {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<TermFinancial> list = termFinancialService.selectAllTermFinancial();
        resultMap.put("termFinancialList", list);
        resultMap.put("pageTopBarInfo", "期限理财界面");
        resultMap.put("activeUrl1", "financeActive");
        resultMap.put("activeUrl2", "termFinancialActive");
        return resultMap;
    }

    /**
     * 期限理财-列表
     */
    @RequestMapping("/fund/list")
    public HashMap<String, Object> fundList() {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<FundProduct> list = fundProductService.selectAllFundProduct();
        resultMap.put("fundProductList", list);
        resultMap.put("pageTopBarInfo", "基金理财界面");
        resultMap.put("activeUrl1", "financeActive");
        resultMap.put("activeUrl2", "fundProductActive");
        return resultMap;
    }

    /**
     * 银行推荐-列表
     *
     * @return
     */
    @RequestMapping("/bank/list")
    public HashMap<String, Object> bankList() {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<Bank> list = bankService.selectAllBank();
        resultMap.put("bankList", list);
        resultMap.put("pageTopBarInfo", "银行推荐界面");
        resultMap.put("activeUrl1", "financeActive");
        resultMap.put("activeUrl2", "bankActive");
        return resultMap;
    }

    /**
     * 资金记录-列表
     */
    @PostMapping("/record/list")
    @ResponseBody
    public HashMap<String, Object> recordList(@RequestBody ApiPaging record) {
        HashMap<String, Object> resultMap = new HashMap<>();
        User tempUser = record.getUser();
        User user = userService.selectUserByTerms(tempUser.getUsername(), tempUser.getPassword());
        Integer pageNum = record.getPageNum();
        Integer pageSize = record.getPageSize();
        // 引入PageHelper插件，在查询之前调用startPage方法，传入页码以及每页大小
        PageHelper.startPage(pageNum, pageSize);
        List<FlowOfFunds> list = flowOfFundsService.selectFlowOfFundsByUserId(user.getId());
        // 使用PageInfo包装查询后的结果，并交给页面处理
        // PageInfo封装了详细的分页信息，包括我们查询出来的数据，还可以传入连续显示的页数（5）
        PageInfo<FlowOfFunds> pageInfo = new PageInfo<FlowOfFunds>(list, 5);
        resultMap.put("flowOfFundsList", list);
        resultMap.put("flowOfFundsPageInfo", pageInfo);
        resultMap.put("pageTopBarInfo", "资金记录界面");
        resultMap.put("activeUrl1", "toolsActive");
        resultMap.put("activeUrl2", "recordActive");
        return resultMap;
    }

    /**
     * 零钱理财-add
     */
    @PostMapping("/change/buyChangeMoney")
    @ResponseBody
    public boolean buyChangeMoney(@RequestBody ApiChange apiChange) {
        ChangeMoney cm = changeMoneyService.selectChangeMoneyById(apiChange.getChangeMoneyId());
        User user = apiChange.getUser();
        User loginUser = userService.selectUserByTerms(user.getUsername(), user.getPassword());
        UserChangeMoney ucm = new UserChangeMoney();
        ucm.setUserid(loginUser.getId());
        ucm.setChangeid(apiChange.getChangeMoneyId());
        ucm.setStarttime(new Date());
        ucm.setAveryield(cm.getAnnualincome());
        ucm.setProfit(cm.getAnnualincome().multiply(cm.getInvesmoney()));
        ucm.setStatus(1);
        Integer result = userChangeMoneyService.insertUserChangeMoney(ucm);
        if (result == 1) {
            FlowOfFunds fof = new FlowOfFunds();
            fof.setUserid(loginUser.getId());
            fof.setFlowmoney(cm.getInvesmoney());
            fof.setType(1);
            fof.setSource(cm.getName());
            fof.setCreatetime(new Date());
            fof.setFunddesc("无");
            flowOfFundsService.insertFlowOfFunds(fof);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 工资理财-add
     */
    @PostMapping("/salary/buyPayMoney")
    @ResponseBody
    public boolean buyPayMoney(@RequestBody ApiSalary apiSalary) {
        PayMoney pm = payMoneyService.selectPayMoneyById(apiSalary.getPayMoneyId());
        User user = apiSalary.getUser();
        User loginUser = userService.selectUserByTerms(user.getUsername(), user.getPassword());
        UserPayMoney upm = new UserPayMoney();
        upm.setUserid(loginUser.getId());
        upm.setPayid(apiSalary.getPayMoneyId());
        upm.setStarttime(new Date());
        upm.setAveryield(new BigDecimal("0.03123"));
        upm.setProfit(new BigDecimal("0.03123").multiply(pm.getMonthmoney()));
        upm.setStatus(1);
        Integer result = userPayMoneyService.insertUserPayMoney(upm);
        if (result == 1) {
            FlowOfFunds fof = new FlowOfFunds();
            fof.setUserid(loginUser.getId());
            fof.setFlowmoney(pm.getMonthmoney());
            fof.setType(1);
            fof.setSource("工资理财");
            fof.setCreatetime(new Date());
            if (pm.getType() == 1) {
                fof.setFunddesc("国债");
            } else if (pm.getType() == 2) {
                fof.setFunddesc("期货");
            }
            flowOfFundsService.insertFlowOfFunds(fof);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 期限理财-add
     */
    @PostMapping("/term/buyTermFinancial")
    @ResponseBody
    public boolean buyTermFinancial(@RequestBody ApiTerm apiTerm) {
        User user = apiTerm.getUser();
        User loginUser = userService.selectUserByTerms(user.getUsername(), user.getPassword());
        UserTermFinancial utf = new UserTermFinancial();
        utf.setUserid(loginUser.getId());
        utf.setTermid(apiTerm.getTermFinancialId());
        utf.setStarttime(new Date());
        TermFinancial tf = termFinancialService.selectTermFinancialById(apiTerm.getTermFinancialId());
        utf.setAveryield(tf.getAnnualincome());
        utf.setProfit(tf.getAnnualincome().multiply(tf.getLeastmoney()));
        utf.setStatus(1);
        Integer result = userTermFinancialService.insertUserTermFinancial(utf);
        if (result == 1) {
            FlowOfFunds fof = new FlowOfFunds();
            fof.setUserid(loginUser.getId());
            fof.setFlowmoney(tf.getLeastmoney());
            fof.setType(1);
            fof.setSource(tf.getName());
            fof.setCreatetime(new Date());
            fof.setFunddesc("无");
            flowOfFundsService.insertFlowOfFunds(fof);
            return true;
        }
        return false;
    }

    /**
     * 基金理财-add
     */
    @PostMapping("/fund/buyFundProduct")
    @ResponseBody
    public boolean buyFundProduct(@RequestBody ApiFund apiFund) {
        User user = apiFund.getUser();
        User loginUser = userService.selectUserByTerms(user.getUsername(), user.getPassword());
        Integer userId = loginUser.getId();
        Integer fundProductId = apiFund.getFundProductId();
        UserFundProduct ufp = new UserFundProduct();
        ufp.setUserid(userId);
        ufp.setFundid(fundProductId);
        ufp.setStarttime(new Date());
        FundProduct fp = fundProductService.selectFundProductById(fundProductId);
        ufp.setAveryield(fp.getMonthlygrowth());
        ufp.setProfit(fp.getLeastmoney().multiply(fp.getMonthlygrowth()));
        ufp.setStatus(1);
        Integer result = userFundProductService.insertUserFundProduct(ufp);
        if (result == 1) {
            FlowOfFunds fof = new FlowOfFunds();
            fof.setUserid(userId);
            fof.setFlowmoney(fp.getLeastmoney());
            fof.setType(1);
            fof.setSource(fp.getFunddesc());
            fof.setCreatetime(new Date());
            fof.setFunddesc("无");
            flowOfFundsService.insertFlowOfFunds(fof);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 我的消息界面
     */
    @PostMapping("/user/message")
    @ResponseBody
    public HashMap<String, Object> toMyInfo(@RequestBody ApiPaging apiPaging) {
        HashMap<String, Object> resultMap = new HashMap<>();
        User user = apiPaging.getUser();
        User loginUser = userService.selectUserByTerms(user.getUsername(), user.getPassword());
        PageHelper.startPage(apiPaging.getPageNum(), apiPaging.getPageSize());
        List<Info> list = infoService.selectInfoOrderByUserIdDesc(loginUser.getId());
        PageInfo<Info> pageInfo = new PageInfo<Info>(list, 5);
        resultMap.put("infoPageInfo", pageInfo);
        resultMap.put("infoList", list);
        resultMap.put("pageTopBarInfo", "我的消息界面");
        return resultMap;
    }

    /**
     * 我的消息界面
     */
    @PostMapping("/user/message/nopage")
    @ResponseBody
    public HashMap<String, Object> toMyInfo(@RequestBody User user) {
        HashMap<String, Object> resultMap = new HashMap<>();
        User loginUser = userService.selectUserByTerms(user.getUsername(), user.getPassword());
        List<Info> list = infoService.selectInfoOrderByUserIdDesc(loginUser.getId());
        resultMap.put("infoPageInfo", list);
        resultMap.put("infoList", list);
        resultMap.put("pageTopBarInfo", "我的消息界面");
        return resultMap;
    }

}
